import retry from 'promise-retry';
import logger from './logger';
import axios from 'axios';

async function getRetryOptions(retries = 5) {
  const retryOptions = {
    retries,
    factor: 2,
    minTimeout: 10 * 1000,
    randomize: true
  };

  return retryOptions;
}

export async function promiseRetry(fn, retries = 5) {
  const retryOptions = await getRetryOptions(retries);
  return retry(fn, retryOptions);
}

export async function postRetry(url: string, data: unknown): Promise<any> {
  logger.debug(`post retry: send http post to ${url}`);
  return await promiseRetry(async(retry, times) => {
    try {
      return await axios.post(url, data, { maxBodyLength: Infinity });
    } catch (ex) {
      logger.error(ex.message);
      logger.info(`retry ${times} times`);
      retry(ex);
    }
  }, 5);
}
